package com.tech.mapper.tem.imp;

import com.tech.repository.entity.User;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class UserDaoMysqlImp extends BasicDaoImp<User> {

	public User getUser(int id) {
		// String sql = "select * from userinfo where uid=?";
		// User user = null;
		// Connection connection = JDBCUtil.getConnection();
		// PreparedStatement statement = null;
		// ResultSet rs = null;
		// try {
		// 	statement = connection.prepareStatement(sql);
		// 	statement.setInt(1, id);
		// 	rs = statement.executeQuery();
		// 	if (rs.next()) {
		// 		user = new User(rs.getInt("uid"),
		// 				rs.getString("uname"),
		// 				rs.getString("upassword").toCharArray(),
		// 				rs.getString("uemail"));
		// 	}
		// } catch (Exception e) {
		// 	e.printStackTrace();
		// } finally {
		// 	JDBCUtil.close(connection, statement, rs);
		// }
		// return user;

		// 上面的替代版本，由SqlTask来执行数据库操作，统一处理异常信息，去除重复代码
		// 但是每个方法都创建了匿名类，不知道会对性能有什么影响，代码可读性也许会变差
		SqlTask<Integer, User> sqlTask = (item, data) -> {
			String sql = "select * from userinfo where uid=?";
			User user = null;
			PreparedStatement statement = item.prepareStatement(sql);
			statement.setInt(1, data);
			ResultSet rs = item.executeQuery();
			if (rs.next()) {
				user = getInstance(rs);
			}
			return user;
		};
		// 执行sql语句
		return SqlTask.processSql(sqlTask, id);
	}


	public List<User> getAllUsers() {
		SqlTask<Object, List<User>> sqlTask = (item, data) -> {
			String sql = "select * from userinfo";
			List<User> list = new ArrayList<>();
			item.prepareStatement(sql);
			ResultSet rs = item.executeQuery();
			while (rs.next()) {
				list.add(getInstance(rs));
			}
			return list;
		};
		return SqlTask.processSql(sqlTask, null);
	}


	public int addUser(User user) {
		SqlTask<User, Integer> sqlTask = (item, data) -> {
			String sql = "insert into userinfo(uname, upassword, uemail) values (?,?,?)";
			int newId = -1;
			PreparedStatement statement = item.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			statement.setString(1, data.getName());
			statement.setString(2, new String(data.getPassword()));
			statement.setString(3, data.getEmail());
			if (statement.executeUpdate() == 1) { //新学生添加成功
				// 获取新添加成员的ID
				ResultSet generatedKeys = item.getGeneratedKeys();
				if (generatedKeys.next()) {
					newId = generatedKeys.getInt(1);
				}
			}
			return newId;
		};
		return SqlTask.processSql(sqlTask, user);
	}


	public int[] addUsers(List<User> usersList) {
		SqlTask<List<User>, int[]> sqlTask = (item, data) -> {
			String sql = "insert into userinfo(uname, upassword, uemail) values (?,?,?)";
			int[] result = null;
			PreparedStatement statement = item.prepareStatement(sql);
			for (User user : data) {
				statement.setString(1, user.getName());
				statement.setString(2, new String(user.getPassword()));
				statement.setString(3, user.getEmail());
				statement.addBatch();
			}
			result = statement.executeBatch();
			return result;
		};
		return SqlTask.processSql(sqlTask, usersList);
	}


	public boolean delUser(int id) {
		SqlTask<Integer, Boolean> sqlTask = (item, data) -> {
			String sql = "delete from userinfo where uid = ?";
			boolean result = false;
			PreparedStatement statement = item.prepareStatement(sql);
			statement.setInt(1, data);
			if (statement.executeUpdate() > 0) {
				result = true;
			}
			return result;
		};
		return SqlTask.processSql(sqlTask, id);
	}


	public boolean delUser(String name) {
		SqlTask<String, Boolean> sqlTask = (item, data) -> {
			String sql = "delete from userinfo where uname = ?";
			boolean result = false;
			PreparedStatement statement = item.prepareStatement(sql);
			statement.setString(1, data);
			if (statement.executeUpdate() > 0) {
				result = true;
			}
			return result;
		};
		return SqlTask.processSql(sqlTask, name);
	}


	public int[] delUsers(List<Integer> usersList) {
		SqlTask<List<Integer>, int[]> sqlTask = (item, data) -> {
			String sql = "delete from userinfo where uid = ?";
			int[] result = null;
			PreparedStatement statement = item.prepareStatement(sql);

			for (Integer usedId : usersList) {
				statement.setInt(1, usedId);
				statement.addBatch();
			}
			result = statement.executeBatch();
			return result;
		};
		return SqlTask.processSql(sqlTask, usersList);
	}


	public boolean delAllUsers() {
		SqlTask<Object, Boolean> sqlTask = (item, data) -> {
			String sql = "delete from userinfo where true";
			PreparedStatement statement = item.prepareStatement(sql);
			statement.executeUpdate();
			return true;
		};
		return SqlTask.processSql(sqlTask, null);
	}


	public int userAuthenticate(User user) {
		SqlTask<User, Integer> sqlTask = (item, data) -> {
			String sql = "select * from userinfo where uname = ? and upassword = ?";
			int userId = -1;
			PreparedStatement statement = item.prepareStatement(sql);
			statement.setString(1, data.getName());
			statement.setString(2, new String(data.getPassword()));
			ResultSet rs = item.executeQuery();
			if (rs.next()) {
				userId = rs.getInt("uid");
			}
			return userId;
		};
		return SqlTask.processSql(sqlTask, user);
	}


	protected User getInstance(ResultSet rs) throws SQLException {
		return new User(rs.getInt("uid"),
				rs.getString("uname"),
				rs.getString("upassword").toCharArray(),
				rs.getString("uemail"));
	}
}
